// pages/calc/calc.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    num:'0',
    op:'',
    btns:[
      {btap:'resetBtn',val:'',title:'C'},
      {btap:'delBtn',val:'',title:'Del'},
      {btap:'opBtn',val:'%',title:'%'},
      {btap:'opBtn',val:'/',title:'÷'},
      {btap:'numBtn',val:'7',title:'7'},
      {btap:'numBtn',val:'8',title:'8'},
      {btap:'numBtn',val:'9',title:'9'},
      {btap:'opBtn',val:'*',title:'*'},
      {btap:'numBtn',val:'4',title:'4'},
      {btap:'numBtn',val:'5',title:'5'},
      {btap:'numBtn',val:'6',title:'6'},
      {btap:'opBtn',val:'-',title:'-'},
      {btap:'numBtn',val:'1',title:'1'},
      {btap:'numBtn',val:'2',title:'2'},
      {btap:'numBtn',val:'3',title:'3'},
      {btap:'opBtn',val:'+',title:'+'},
      {btap:'numBtn',val:'0',title:'0'},
      {btap:'dotBtn',val:'.',title:'.'},
      {btap:'opBtn',val:'=',title:'='},
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  result:null,
  isClear:false,
  numBtn:function(e){
    var num = e.target.dataset.value
    if(this.data.num === '0' || this.isClear){
      this.setData({num:num})
      this.isClear = false
    }else{
      this.setData({num:this.data.num+num})
    }
  },
  opBtn:function(e){
    var op = this.data.op
    var num = Number(this.data.num)
    this.setData({op:e.target.dataset.value})
    if(this.isClear){
      return
    }
    this.isClear = true
    if(this.result === null){
      this.result = num
      return
    }
    if(op === '+'){
      this.result = this.result + num
    }else if(op === '-'){
      this.result = this.result - num
    }else if(op === '*'){
      this.result = this.result * num
    }else if(op === '÷'){
      this.result = this.result / num
    }else if(op === '%'){
      this.result = this.result % num
    }
    this.setData({num:this.result+''})
  },
  dotBtn:function(){
    if(this.clear){
      this.setData({num:'0.'})
      this.isClear = false
      return
    }
    if(this.data.num.indexOf('.')>=0){
      return
    }
    this.setData({num:this.data.num+'.'})
  },
  delBtn:function(){
    var num = this.data.num.substr(0,this.data.num.length-1)
    this.setData({num:num===''?'0':num})
  },
  resetBtn:function(){
    this.result = null
    this.isClear = false
    this.setData({num:'0',op:''})
  }
})